import clientEnum from "./client.enum"
import SimplePostMessage from "./SimplePostMessage"

export default class InjectRoutine {
  clientId: number
  key: string
  argsDef: { argNames: string[]; varArg: boolean }
  constructor() {
    this.clientId = Math.floor(1e6 * Math.random())
    this.key = "mattertag.inject"
    this.argsDef = { argNames: ["tagId", "html", "options"], varArg: !1 }
  }
  buildMessageData(t, e) {
    return Object.assign(Object.assign({}, e), { clientId: this.clientId })
  }
  onResponse(t, e) {
    return new Promise(t => {
      let s
      if (e.messengerType === clientEnum.et.POSTMESSAGE) {
        const e = e => {
          const { toId: i, fromId: r } = e.data
          i === this.clientId &&
            e.data.type === clientEnum.tt.RESOLVE &&
            (s ? s.updateTarget(e.source) : ((s = new SimplePostMessage(this.clientId, r, e.source)), t(s.facade())))
        }
        window.addEventListener("message", e)
      }
    })
  }
}
